<template>
  <div class="app-container">
    <el-tree
      :data="tree"
      node-key="id"
      show-checkbox
      :default-checked-keys="[checked]"
      :default-expanded-keys="[checked]"
      :expand-on-click-node="false">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ data.text }} ({{data.id}})</span>
        <span>
          <el-button
            type="text"
            size="mini"
            @click="() => save(data)">
            保存
          </el-button>
        </span>
      </span>
    </el-tree>
  </div>
</template>

<script>
import api from '@/api'

export default {
  name: 'MemberArea',
  data() {
    return {
      tree: [],
      checked: 0
    }
  },
  mounted() {
    this.getTree()
    this.getChecked()
  },
  methods: {
    /**
     * 分类列表
     */
    getTree() {
      const key = 'city-tree'
      const tree = window.localStorage.getItem(key)
      if (tree) {
        this.tree = JSON.parse(tree)
      } else {
        api.member.getTree().then(response => {
          this.tree = response.data.tree
          window.localStorage.setItem(key, JSON.stringify(this.tree))
        })
      }
    },
    getChecked() {
      api.member.getChecked({ user_id: this.$route.params.id }).then(response => {
        this.checked = response.data.address_id
      })
    },
    /**
     * 修改
     * @param row
     */
    save(data) {
      console.log(data)

      const x = ['500000', '110000', '120000', '310000']
      if (!x.includes(data.province_id)) {
        if (!data.area_id) {
          return this.$message.error('请选择区')
        }
      }

      const user_id = this.$route.params.id
      api.member.saveChecked({
        user_id,
        address_id: data.id
      }).then(() => {
        this.checked = data.id
        // console.log(this.checked)
        this.$message.success('操作成功')
        this.$router.push(`/member/area/${this.$route.params.id}?t=${new Date().getTime()}`)
      })
    }
  },
  /**
   * 刷新
   * @param to
   * @param from
   * @param next
   */
  beforeRouteUpdate(to, from, next) {
    if (to.path === from.path) {
      const newQuery = Object.assign({}, to.query)
      const oldQuery = Object.assign({}, from.query)
      if (JSON.stringify(newQuery) !== JSON.stringify(oldQuery)) {
        this.getTree()
      }
    }
    next()
  }
}
</script>

<style scoped lang="scss">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 10px;
}
</style>

